<template>
    <view class="deliveryAddress">
        <radio-group @change="radioChange">
            <view 
                v-for="(item, index) in formGroup" 
                :key="index"
                class="box"
            >
                <view @click.stop="goBack(item)">
                    <view class="main-header">
                        <view class="main-header-name">
                            {{item.receiver}}
                        </view>
                        <view class="main-header-phone">
                            {{item.mobile}}
                        </view>
                    </view>
                    <view class="main-address">
                       <!--  {{item.zsa_ex5}} -->
                        {{item.detailAddress}}
                    </view>
                </view>
                <label class="main-footer">
                    <view class="main-footer-left">
                        <radio 
                            :value="item.id" 
                            :checked="index === currentIdx" 
                        />
                        <view>默认地址</view>
                    </view>
                    <view class="main-footer-right">
                        <view 
                            class="main-footer-right-1"
                            @click.stop="addEdit(item)"
                        >
                            <view class="iconfont icon-bianji"></view>
                            <view class="main-footer-right-1-text">编辑</view>
                        </view>
                        <view 
                            class="main-footer-right-2"
                            @click.stop="del(item, index)"
                        >
                            <view class="iconfont icon-shanchu"></view>
                            <view class="main-footer-right-2-text">删除</view>
                        </view>
                    </view>
                </label>
                
            </view>
        </radio-group>
        <button
            class="btn-1"
            @click="addEdit()" 
        >
            添加收货地址
        </button>
        
        <uni-popup
            ref="popup1" 
            type="center"
            :is-mask-click="true"
        >
            <view class="my-popup-box">
                <uni-forms
                    :model="formData" 
                    ref="form" 
                    :rules="rules1" 
                    validateTrigger="submit" 
                    label-width="150rpx"
                    err-show-type='none'
                >
                    <view class="box-1">
                        <uni-section
                            type="line"
                            title="收货信息" 
                            sub-title=""
                        >
                        </uni-section>
                        <uni-forms-item
                            name="receiver"
                            label="收货人"
                            required
                        >
                            <uni-easyinput 
                                v-model="formData.receiver"
                                type="text" 
                                placeholder="请输入收货人" 
                            />
                        </uni-forms-item>
                        <uni-forms-item
                            name="mobile"
                            label="手机号"
                            required
                        >
                            <uni-easyinput 
                                v-model="formData.mobile"
                                maxlength="11"
                                type="digit" 
                                placeholder="请输入手机号" 
                            />
                        </uni-forms-item>
                        <!-- <uni-forms-item
                            name="zsa_ex5"
                            label="收货地址"
                            required
                        >
                            <view 
                                class="point-box" 
                                @click="chooseLocation('zsa_ex5', 'zo_ex17')"
                            >
                                <view 
                                    class="point-box-text point-box-text-1" 
                                >
                                    {{ formData.zsa_ex5 ? formData.zsa_ex5 :'请选择收货地址' }}
                                </view>
                                <view class="iconfont icon-dizhi" />
                            </view>
                        </uni-forms-item> -->
                        <uni-forms-item
                            name="detailAddress"
                            label="详细地址"
                            required
                        >
                            <uni-easyinput 
                                v-model="formData.detailAddress"
                                type="text" 
                                placeholder="请输入详细地址" 
                            />
                        </uni-forms-item>
                    </view>
                    <button
                        @click="onSubmit"
                        style="background-color: #c83b45; color: #ffffff; font-size: 28rpx; padding: 10rpx;"
                    >
                        <view style="font-weight: bold;">确认</view>
                    </button>
                 </uni-forms>
            </view>
        </uni-popup>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
    import { markRaw, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { isPhone } from '@/utils/utils'
    import { getAddressesApi, postAddressesApi,putAddressesIdApi, deleteAddressesIdApi,putAddressesIdSetDefaultApi } from '@/apis'
    import { qqMapTransBMap } from '@/utils/utils'
    
    const popup1: Ref<any> = ref(null)
    const form: Ref<any> = ref(null)
    const formOldData: Ref<any> = ref({
        receiver: '', //收货人
        mobile: '', //手机号
        // zsa_ex5: '', //地址
        detailAddress: '', //详细地址
        zo_ex17: '', //经纬度
    })
    const formData: Ref<any> = ref({
        receiver: '', //收货人
        mobile: '', //手机号
        // zsa_ex5: '', //地址
        detailAddress: '', //详细地址
        zo_ex17: '', //经纬度
    })
    const rules1: any = reactive({
        mobile: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入手机号',
                },{
                    validateFunction: function(rule, value, data, callback){
                        if (!isPhone(value)) {
                            callback('请输入正确的手机号')
                        }
                        return true
                    }
                }
            ],
        },
        receiver: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入收货人',
                }
            ],
        },
        // zsa_ex5: {
        //     rules: [
        //         {
        //             required: true,
        //             errorMessage: '请选择收货地址',
        //         }
        //     ],
        // },
    })
    const currentIdx: Ref<number> = ref(0)
    const pageUrl: Ref<string> = ref('')
    const formGroup: Ref<any[]> = ref([
        // {
        //     receiver: '姓名啊啊',
        //     mobile: '15200000000',
        //     zsa_ex5: 'xxx省xx市xx县xxxxxxxxxx',
        //     detailAddress: '', //详细地址
        //     zo_ex17: '', //经纬度
        //     id: 1,
        // },
        // {
        //     receiver: '姓名2啊',
        //     mobile: '16200000000',
        //     zsa_ex5: 'xx省xx市xx县xxxxxxxxxx',
        //     detailAddress: '', //详细地址
        //     zo_ex17: '', //经纬度
        //     id: 2
        // }
    ])
	   
    
    onLoad((val: any) => {
        console.log(val)
        if (val.pageUrl) {
            pageUrl.value = val.pageUrl
        }
        
        getAddressesApi({
        }).then((res: any) => {
           console.log(res.data)
           formGroup.value = res.data
           for (let i = 0; i < formGroup.value.length; i++) {
               if (formGroup.value[i].isDefault == true ) {
                   currentIdx.value = i;
                   break;
               }
           }
        }).finally(() => {
        })
    })
    // 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则
    onReady(() => {
        form.value.setRules(rules1)
    })
    
    const radioChange = (evt: any) => {
        console.log(evt)
        for (let i = 0; i < formGroup.value.length; i++) {
            console.log(formGroup.value[i])
            if (formGroup.value[i].id === evt.detail.value) {
                currentIdx.value = i;
                formGroup.value[i].isDefault = true //默认地址
                console.log(formGroup.value[i])
                formData.value = formGroup.value[i]
                putAddressesIdSetDefaultApi(formGroup.value[i].id)
                // break;
            } else {
                formGroup.value[i].isDefault = false //默认地址
            }
        }
        
    }
    const goBack = (val?: any) => {
        console.log(pageUrl.value)
        if (pageUrl.value == '/pages/mine/mine') {
            uni.navigateBack();
        }else if (pageUrl.value) {
            uni.redirectTo({
            	url: pageUrl.value + `?addressId=${val.id}&address=${val.receiver}，${val.mobile}，${val.detailAddress}`
            });
        }
        
    }
    const addEdit = (val?: any) => {
        // 编辑地址
        if (val) {
            // 编辑
            formData.value = JSON.parse(JSON.stringify(val))
            formOldData.value = val
            popup1.value.open()
        } else {
            // 新增
            formData.value = JSON.parse(JSON.stringify(formData.value))
            formOldData.value = JSON.parse(JSON.stringify(formData.value))
            Object.keys(formData.value).forEach((item, index) => {
                formData.value[item] = ''
                formOldData.value[item] = ''
            })
            popup1.value.open()
        }
    }
    const del = (val: any, index: number) => {
        if (index == currentIdx.value) {
            uni.showModal({
                showCancel: false,
                title: '温馨提示',
                content: '默认地址无法删除！', 
                success: function (res) {
                    console.log('用户点击确定');
                }
            });
        } else {
            uni.showModal({
                showCancel: true,
                title: '温馨提示',
                content: '是否确认删除？', 
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                        // 调删除接口
                        formGroup.value.splice(index, 1)
                        deleteAddressesIdApi(val.id)
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
        
    }
    const onSubmit = () => {
        form.value.validate().then(async(res1: any) => {
            if (formData.value.id) {
                // 调接口
                putAddressesIdApi(formData.value.id,{
                    ...formData.value
                }).then(res2 => {
                    Object.keys(formOldData.value).forEach((item, index) => {
                        formOldData.value[item] = formData.value[item]
                    })
                    popup1.value.close()
                }).catch(err2 => {
                    uni.showToast({
                        title: '修改地址失败！',
                        icon: 'error',
                        duration: 1500,
                        mask: true,
                    });
                })
            } else {
                // 调接口
                postAddressesApi({
                    ...formData.value
                }).then(res2 => {
                    formGroup.value.push(formData.value)
                    popup1.value.close()
                }).catch(err2 => {
                    uni.showToast({
                        title: '添加地址失败！',
                        icon: 'error',
                        duration: 1500,
                        mask: true,
                    });
                })
            }
            
        }).catch((err1: any) =>{
            console.log('表单错误信息：', err1);
            uni.showToast({
                title: err1[0].errorMessage,
                icon: 'error',
                duration: 1500,
                mask: true,
            });
        })
    }
    const chooseLocation = (val1: string, val2: string,) => {
        console.log(val1)
        console.log(val2)
        // console.log(latitude.value)
        // console.log(longitude.value)
        uni.authorize({
            scope: 'scope.userLocation',
            success() {
                console.log('定位')
                uni.chooseLocation({
                    success: (res) => {
                        console.log(res)
                        console.log('位置名称：' + res.name);
                        console.log('详细地址：' + res.address);
                        console.log('纬度：' + res.latitude);
                        console.log('经度：' + res.longitude);
                        formData.value[val1] = res.address + res.name
                        let obj = qqMapTransBMap(res.longitude, res.latitude)
                        formData.value[val2] = obj.longitude + ',' + obj.latitude
                    }
                })
            },
            fail() {
                uni.getSetting({
                    success(res) {
                        console.log(res)
                        if (!res.authSetting['scope.userLocation']) {
                            uni.showModal({
                                showCancel: true,
                            	title: '温馨提示',
                            	content: '需要授权位置信息!',
                            	success: function (res) {
                            		if (res.confirm) {
                            			console.log('用户点击确定');
                                        uni.openSetting()
                            		} else if (res.cancel) {
                            			console.log('用户点击取消');
                            		}
                            	}
                            });
                        }
                    }
                })
            }
        })
    }
</script>

<style lang="scss" scoped>
    .deliveryAddress {
        min-height: 100vh;
        background-color: #f2f2f2;
        display: flex;
        flex-direction: column;
    }
    .box {
        background: #fff;
        box-sizing: border-box;
        padding: 20rpx;
        margin-top: 10rpx;
        .main-header {
            padding: 10rpx 0;
            display: flex;
            .main-header-phone {
                padding-left: 20rpx;
            }
        }
        .main-address {
            padding: 10rpx 0;
            color: #999999;
            border-bottom: 1rpx solid #d8c7c7;
        }
        .main-footer {
            padding: 10rpx 0;
            display: flex;
            justify-content: space-between;
            .main-footer-left {
                display: flex;
                align-items: center;
            }
            .main-footer-right {
                display: flex;
                color: #999999;
                .main-footer-right-1 {
                    display: flex;
                    align-items: center;
                    .main-footer-right-1-text {
                        padding-left: 10rpx;
                    }
                }
                .main-footer-right-2 {
                    display: flex;
                    align-items: center;
                    margin-left: 20rpx;
                    .main-footer-right-2-text {
                        padding-left: 10rpx;
                    }
                }
            }
        }
    }
    .my-popup-box {
        background: #fff;
        width: 700rpx; 
        box-sizing: border-box; 
        padding: 40rpx;
        // padding: 0 0 30rpx 0; 
        border-radius: 40rpx;
        .point-box {
            height: 100%;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            .point-box-text {
                // margin-left: 20rpx;
                // font-weight: bold;
                // font-size: 40rpx;
                width: 100%;
                padding-left: 20rpx;
            }
            .point-box-text-1 {
                color: #c83b45;
            }
        }
    }
    .btn-1 {
        font-size: 28rpx;
        margin-top: 20rpx; 
        background: #c83b45; 
        color: #fff;
        width: 80%;
        padding: 10rpx;
    }
</style>
